const app = getApp()

// Helper function for navigation based on item text
function navigateToServicePage(itemText) {
  switch (itemText) {
    case '报修':
      wx.navigateTo({ url: '/pages/repair/repair' });
      break;
    case '进度查询':
      wx.navigateTo({ url: '/pages/progress/progress' });
      break;
    case '历史订单':
      wx.navigateTo({ url: '/pages/history/history' });
      break;
    case '个人中心':
      wx.navigateTo({ url: '/pages/mine/mine' });
      break;
    case '联系客服':
      wx.navigateTo({ url: '/pages/contact/contact' });
      break;
    case '设置':
      wx.navigateTo({ url: '/pages/mine/settings/settings' }); // 假设用户设置页面路径
      break;
    case '常见问题':
      wx.navigateTo({ url: '/pages/faq/faq' });
      break;
    case '意见反馈':
      wx.navigateTo({ url: '/pages/feedback/feedback' });
      break;
    case '关于我们':
      wx.navigateTo({ url: '/pages/about/about' });
      break;
    default:
      // 对于一般的推荐服务（如空调维修），跳转到报修页面并带上服务名
      wx.navigateTo({ url: '/pages/repair/repair?service=' + encodeURIComponent(itemText) });
      break;
  }
}

Page({
  data: {
    userInfo: null,
    searchValue: '',
    searchResults: [],
    banners: [
      'https://img.yzcdn.cn/vant/apple-1.jpg',
      'https://img.yzcdn.cn/vant/apple-2.jpg',
      'https://img.yzcdn.cn/vant/apple-3.jpg'
    ],
    gridList: [
      { icon: 'https://img.icons8.com/color/96/000000/maintenance.png', text: '报修' },
      { icon: 'https://img.icons8.com/color/96/000000/search--v1.png', text: '进度查询' },
      { icon: 'https://img.icons8.com/color/96/000000/order-history.png', text: '历史订单' },
      { icon: 'https://img.icons8.com/color/96/000000/user.png', text: '个人中心' },
      { icon: 'https://img.icons8.com/color/96/000000/phone.png', text: '联系客服' },
      { icon: 'https://img.icons8.com/color/96/000000/settings.png', text: '设置' },
      { icon: 'https://img.icons8.com/color/96/000000/faq.png', text: '常见问题' },
      { icon: 'https://img.icons8.com/color/96/000000/feedback.png', text: '意见反馈' },
      { icon: 'https://img.icons8.com/color/96/000000/info.png', text: '关于我们' }
    ],
    popularServices: [
      { img: 'https://img.icons8.com/color/96/000000/air-conditioner.png', text: '空调清洗' },
      { img: 'https://icons8.com/icon/47696/refrigerator', text: '冰箱维修' },
      { img: 'https://icons8.com/icon/47692/washing-machine', text: '洗衣机维修' },
      { img: 'https://icons8.com/icon/47683/tv', text: '电视安装' },
      { img: 'https://icons8.com/icon/47690/water-heater', text: '热水器安装' }
    ],
    selfServiceGridList: [
      { icon: 'https://img.icons8.com/color/96/000000/bill.png', text: '收费标准' },
      { icon: 'https://img.icons8.com/color/96/000000/warranty.png', text: '包修政策' },
      { icon: 'https://img.icons8.com/color/96/000000/service.png', text: '服务标准' },
      { icon: 'https://img.icons8.com/color/96/000000/marker.png', text: '服务网点' },
      { icon: 'https://img.icons8.com/color/96/000000/bug.png', text: '故障自查' },
    ]
  },
  onShow() {
    // 从全局变量获取用户信息
    this.setData({
      userInfo: getApp().globalData.userInfo || null
    })
  },
  goRepair() {
    wx.navigateTo({
      url: '/pages/repair/repair'
    })
  },
  onGridTap(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.gridList[index];
    navigateToServicePage(item.text); // 使用公共跳转方法
  },
  onServiceTap(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.popularServices[index];
    navigateToServicePage(item.text);
  },
  onSearchInput(e) {
    this.setData({ searchValue: e.detail.value });
  },
  async onSearch() {
    const keyword = this.data.searchValue.trim();
    if (!keyword) {
      wx.showToast({ title: '请输入关键词', icon: 'none' });
      return;
    }
    wx.showLoading({ title: '搜索中...' });
    try {
      // 搜索服务（本地热门服务、九宫格和自助查询）
      const serviceResultsRaw = [
        ...this.data.popularServices.filter(item => item.text.includes(keyword)),
        ...this.data.gridList.filter(item => item.text.includes(keyword)),
        ...this.data.selfServiceGridList.filter(item => item.text.includes(keyword))
      ];

      // 去重
      const serviceResults = [];
      const seenTexts = new Set();
      serviceResultsRaw.forEach(item => {
        if (!seenTexts.has(item.text)) {
          serviceResults.push(item);
          seenTexts.add(item.text);
        }
      });

      // 搜索订单（调用后端接口）
      const userId = wx.getStorageSync('userId');
      let orderResults = [];
      if (userId) {
        const res = await app.request({
          url: `/api/orders/user/${userId}/search?keyword=${encodeURIComponent(keyword)}`,
          method: 'GET'
        });
        orderResults = res.data || [];
      }

      const searchResults = [
        ...serviceResults.map(item => ({ type: 'service', ...item })),
        ...orderResults.map(item => ({ type: 'order', ...item }))
      ];
      this.setData({ searchResults });
      wx.hideLoading();

      if (searchResults.length === 0) {
        wx.showToast({ title: '未找到相关内容', icon: 'none' });
      } else if (searchResults.length === 1) {
        // 只有一个结果，直接跳转
        const result = searchResults[0];
        if (result.type === 'order') {
          const orderId = result.orderNumber || result.orderId || result.id;
          wx.navigateTo({ url: `/pages/orderDetail/orderDetail?orderId=${orderId}` });
        } else if (result.type === 'service') {
          navigateToServicePage(result.text); // 使用公共跳转方法
        }
      } else {
        // 多个结果，跳转到结果列表页
        // 这里可以将 searchResults 存到全局或者通过 eventChannel 传递
        wx.navigateTo({ url: '/pages/index/searchResult' });
      }
    } catch (err) {
      wx.hideLoading();
      wx.showToast({ title: '搜索失败', icon: 'none' });
      console.error('搜索失败:', err);
    }
  },
  onSelfServiceTap(e) {
    const index = e.currentTarget.dataset.index;
    const item = this.data.selfServiceGridList[index];
    switch (item.text) {
      case '收费标准':
        wx.navigateTo({ url: '/pages/query/feeStandard/feeStandard' });
        break;
      case '包修政策':
        wx.navigateTo({ url: '/pages/productSelect/warrantyPolicy/warrantyPolicy' });
        break;
      case '服务标准':
        wx.navigateTo({ url: '/pages/query/serviceStandard/serviceStandard' });
        break;
      case '服务网点':
        wx.navigateTo({ url: '/pages/query/serviceOutlets/serviceOutlets' });
        break;
      case '故障自查':
        wx.navigateTo({ url: '/pages/productSelect/troubleshootSelect/troubleshootSelect' });
        break;
      default:
        console.log('Unhandled self-service item:', item.text);
        break;
    }
  }
}) 